import requests
import logging
logger = logging.getLogger(__name__)

class BDFOP2Helper:
    req_timeout = 20
    def __init__(self, base_uri):
        self.base_uri = base_uri

    def get_bdf_info(self):
        try:
            url = f"{self.base_uri}/bdf?page_num=1&page_size=100"
            response = requests.get(url, timeout=self.req_timeout)
            res = self._handle_response(response)
        except Exception as e:
            raise Exception(f"get_operator_info failed: {e}") from e

        logger.debug("get_operator_info from res helper: %s", res)
        return res

    def get_op2_info(self):
        try:
            url = f"{self.base_uri}/op2?page_num=1&page_size=100"
            response = requests.get(url, timeout=self.req_timeout)
            res = self._handle_response(response)
        except Exception as e:
            raise Exception(f"get algo info failed: {e}") from e

        logger.debug("get algo from res helper: %s", res)
        return res

    def _handle_response(self, response):
        if response.status_code != 200:
            try:
                error_details = response.json()
            except ValueError:
                error_details = {'message': 'cannot decode response by Json'}
            raise Exception(f"HTTP Error {response.status_code}: {error_details.get('message')}")

        result = response.json()
        if not result.get('success', False):
            raise Exception(f"remote return success:false : {result.get('message')}")

        return result['data']['data']
